package com.quasar.hpatient.module.comm_main;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.module.home.HomeView;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelChangeListener;
import lib.quasar.base.http.HttpResult;
import lib.quasar.chat.ChatService;
import lib.quasar.context.BaseApp;
import lib.quasar.db.manager.DBManager;
import lib.quasar.db.table.Chat;
import lib.quasar.util.ServiceUtil;
import okhttp3.RequestBody;

/**
 * description: 入口
 * created by kalu on 2018/4/2 16:01
 */
public class MainPresenter implements BasePresenter {

    private Messenger mMessenger = null;
    private HandlerThread messengerThread = null;
    private ServiceConnection service = null;

    void startThread(){
        messengerThread = new HandlerThread("MessengerThread");
        messengerThread.start();
    }

    void stopThread(){
        if (null != messengerThread){
            messengerThread.stop();
        }
    }

    void bindChatService(MainView view){

        final Intent intent = new Intent(BaseApp.getContext(), ChatService.class);
        service = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.e("WebSocketClient", "接受消息[连接成功] ==> 回调线程 = " + Thread.currentThread().getName());


                mMessenger = new Messenger(service);
//                messengerThread = new HandlerThread("MessengerThread");
//                messengerThread.start();

                final Messenger mClientMessenger = new Messenger(new Handler(messengerThread.getLooper()) {
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case ChatService.TYPE_RETRY:
                                try {
                                    Message obtain = Message.obtain();
                                    obtain.what = ChatService.TYPE_RETRY;
                                    obtain.replyTo = msg.replyTo;
                                    mMessenger.send(obtain);
                                    Log.e("WebSocketClient", "接受消息[连接失败] ==> 回调线程 = " + Thread.currentThread().getName() + " , 客户端向服务端发送重新连接消息");
                                } catch (Exception e) {
                                }
                                break;
                            case ChatService.TYPE_HANDLER:
                                String clientid = msg.getData().getString(ChatService.MESSAGE_CLIENTID);
                                if (!TextUtils.isEmpty(clientid)) {
                                    Log.e("WebSocketClient", "接受消息[握手消息] ==> 回调线程 = " + Thread.currentThread().getName() + " , clientid = " + clientid);
                                    connectCallback(view, clientid, mMessenger);
                                }
                                break;
                            case ChatService.TYPE_MESSAGE:
                                final Chat messageModel = (Chat) msg.getData().getSerializable(ChatService.MESSAGE_MODEL);
                                if (null == messageModel)
                                    break;

                                Log.e("WebSocketClient", "接受消息[聊天消息] ==> 回调线程 = " + Thread.currentThread().getName() + " , message = " + messageModel.toString());
                                view.autoBadgeNumber();
                                final Intent intent = new Intent(ChatService.INTENT_NAME);
                                intent.putExtra(ChatService.MESSAGE_MODEL, messageModel);
                                LocalBroadcastManager.getInstance(BaseApp.getContext()).sendBroadcast(intent);
                                break;
                        }
                    }
                });

                try {
                    Message obtain = Message.obtain();
                    obtain.what = ChatService.TYPE_SUCC;
                    obtain.replyTo = mClientMessenger;
                    mMessenger.send(obtain);
                } catch (Exception e) {
                    Log.e("WebSocketClient", "聊天服务 ==> " + e.getMessage(), e);
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e("WebSocketClient", "聊天服务 ==> 连接失败");
            }
        };

        BaseApp.getContext().bindService(intent, service, Context.BIND_AUTO_CREATE);

    }

    void unbindChatService(){

        try {
            Message obtain = Message.obtain();
            obtain.what = ChatService.TYPE_UNBIND;
            obtain.replyTo = null;
            mMessenger.send(obtain);
        } catch (Exception e) {
            Log.e("WebSocketClient", "聊天服务 ==> " + e.getMessage(), e);
        }

        BaseApp.getContext().unbindService(service);

    }

    final void refreshMessage(MainView view) {
        int messageCount = 0;
        final List<lib.quasar.db.table.Message> messageList = DBManager.getInstance().getMessageList(getPatientId());
        if (null != messageList && !messageList.isEmpty()) {
            for (lib.quasar.db.table.Message temp : messageList) {
                messageCount += temp.getMessage_num();
            }
        }
        view.setBadgeNumber(messageCount);
    }

    void initAdapter(MainView view, FragmentManager manager) {

        if (null == view) return;

        MainAdapter mainAdapter = new MainAdapter(manager);
        view.setPagerAdapter(mainAdapter);

        int messageNumber = 0;
        List<lib.quasar.db.table.Message> messageList = DBManager.getInstance().getMessageList(getPatientId());

        for (lib.quasar.db.table.Message it : messageList) {
            messageNumber += it.getMessage_num();
        }
        view.setMenuPager(messageNumber);
    }

    void startChatService(MainView view) {

        if (ServiceUtil.isServiceRunning(ChatService.class.getSimpleName()))
            return;

        final Intent intent = new Intent(BaseApp.getContext(), ChatService.class);
        BaseApp.getContext().startService(intent);
//
//        BaseApp.getContext().bindService(intent, new ServiceConnection() {
//
//            @Override
//            public void onServiceConnected(ComponentName name, IBinder service) {
//                Log.e("WebSocketClient", "接受消息[连接成功] ==> 回调线程 = " + Thread.currentThread().getName());
//
//
//                final Messenger mMessenger = new Messenger(service);
//                final HandlerThread messengerThread = new HandlerThread("MessengerThread");
//                messengerThread.start();
//
//                final Messenger mClientMessenger = new Messenger(new Handler(messengerThread.getLooper()) {
//                    @Override
//                    public void handleMessage(Message msg) {
//                        switch (msg.what) {
//                            case ChatService.TYPE_RETRY:
//                                try {
//                                    Message obtain = Message.obtain();
//                                    obtain.what = ChatService.TYPE_RETRY;
//                                    obtain.replyTo = msg.replyTo;
//                                    mMessenger.send(obtain);
//                                    Log.e("WebSocketClient", "接受消息[连接失败] ==> 回调线程 = " + Thread.currentThread().getName() + " , 客户端向服务端发送重新连接消息");
//                                } catch (Exception e) {
//                                }
//                                break;
//                            case ChatService.TYPE_HANDLER:
//                                String clientid = msg.getData().getString(ChatService.MESSAGE_CLIENTID);
//                                if (!TextUtils.isEmpty(clientid)) {
//                                    Log.e("WebSocketClient", "接受消息[握手消息] ==> 回调线程 = " + Thread.currentThread().getName() + " , clientid = " + clientid);
//                                    connectCallback(view, clientid, mMessenger);
//                                }
//                                break;
//                            case ChatService.TYPE_MESSAGE:
//                                final Chat messageModel = (Chat) msg.getData().getSerializable(ChatService.MESSAGE_MODEL);
//                                if (null == messageModel)
//                                    break;
//
//                                Log.e("WebSocketClient", "接受消息[聊天消息] ==> 回调线程 = " + Thread.currentThread().getName() + " , message = " + messageModel.toString());
//                                view.autoBadgeNumber();
//                                final Intent intent = new Intent(ChatService.INTENT_NAME);
//                                intent.putExtra(ChatService.MESSAGE_MODEL, messageModel);
//                                LocalBroadcastManager.getInstance(BaseApp.getContext()).sendBroadcast(intent);
//                                break;
//                        }
//                    }
//                });
//
//                try {
//                    Message obtain = Message.obtain();
//                    obtain.what = ChatService.TYPE_SUCC;
//                    obtain.replyTo = mClientMessenger;
//                    mMessenger.send(obtain);
//                } catch (Exception e) {
//                    Log.e("WebSocketClient", "聊天服务 ==> " + e.getMessage(), e);
//                }
//            }
//
//            @Override
//            public void onServiceDisconnected(ComponentName name) {
//                Log.e("WebSocketClient", "聊天服务 ==> 连接失败");
//            }
//        }, Context.BIND_AUTO_CREATE);
    }


    //握手
    void connectCallback(MainView view, String clientid, Messenger clientMessenger) {

        HashMap map = new HashMap<String, Object>();
        map.put("user_type", "p");
        map.put("userid", DBManager.getInstance().syncGetUserModel().getPatientid());
        map.put("client_id", clientid);

        RequestBody params = createParams(map, HttpParams.DATA_TYPE_1_10);
        Observable<HttpResult<Object>> observable = HttpClient.getSingleHolder().getHttpService().uploadData(params);

        request(observable, new OnModelChangeListener() {
            @Override
            public void modelSucc() {
                try {
                    Message obtain = Message.obtain();
                    obtain.what = ChatService.TYPE_HANDLER_SUCC;
                    clientMessenger.send(obtain);
                } catch (Exception e) {
                }
            }

            @SuppressLint("CheckResult")
            @Override
            public void modelFail() {

                try {
                    Message obtain = Message.obtain();
                    obtain.what = ChatService.TYPE_HANDLER_FAIL;
                    clientMessenger.send(obtain);
                    Observable.timer(500, TimeUnit.MICROSECONDS).subscribe(aLong -> connectCallback(view, clientid, clientMessenger));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    //获取用户信息
    void loadPatientInfo(MainView view) {
//        HashMap<String, Object> map = new HashMap<>();
//        Long userid = DBManager.getInstance().syncGetUserModel().getPatientid();
//        map.put(HttpParams.USER_ID, userid);
//        map.put(HttpParams.USER_TYPE, BaseConstant.TWO);
//        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_1_2);
//        final Observable observable = HttpClient.getSingleHolder().getHttpService().getUserInfo(params);
//
//        request(observable, new OnModelAcceptChangeListener<PatientInfoBean>() {
//
//            @Override
//            public void modelFail() {
//                view.toast("获取个人信息失败");
//            }
//
//            @Override
//            public void modelSucc(PatientInfoBean model) {
//                view.toast("获取个人信息成功");
//                //保存用户名
//                DBManager.getInstance().updataUserModel(model);
//            }
//        });
    }

    @Override
    public void recycler() {
    }
}
